﻿using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using EeekSoft.Web;
using Resources;
using Service;

public partial class EquipmentDisplay : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        txtHiddenEquipmentId.Text = Request.QueryString["equipmentId"];
        if (Session["whereClause"] == null)
            Session["whereClause"] = txtHiddenWhereClause.Text;
        if (Session["orderByClause"] == null)
            Session["orderByClause"] = txthiddenOrderbyClause.Text;

        //configuration for setting row to display
        new Utility().SetRowToDisplay(grdEquipment, Session["rowsToSDisplay"]);

        if (!IsPostBack)
        {
            Session["equipmentId"] = Request.QueryString["equipmentId"];
            Session["defaultTabIndex"] = Request.QueryString["tabIndex"];
            DisplayPopUp("There are " +
                         new DirectService().GetEquipmentWarrantyAlertBeforeMonth(
                             Int32.Parse(Resource.NumberOfMonthToAlert)).Rows.Count +
                         " equipments going to be out of warranty in " + Resource.NumberOfMonthToAlert + " month(s).");
            // to avoid loading for the first time
            if ((Request.QueryString["detail"] == null))
            {
                if ((Request.QueryString["delete"] == null))
                {
                    txtHiddenWhereClause.Text = "and Equipement.codeNumber='0'";
                    lblTotalEquipment.Text = "Total Equipments : 0";
                }
                else
                {
                    if (!new Utility().TestPermissions(Resource.PermissionDeleteEquipment))
                    {
                        lblpermissiondelete.Text = Resource.Permission;
                        lblTotalEquipment.Visible = false;
                        return;
                    }
                    int equipmentId = Request.QueryString["equipmentId"] != null
                                          ? Int32.Parse(Request.QueryString["equipmentId"])
                                          : 0;
                    new StockService().Delete(equipmentId);
                    txtHiddenWhereClause.Text = Session["whereClause"].ToString();
                    txthiddenOrderbyClause.Text = Session["orderByClause"].ToString();
                }
            }
            else
            {
                txtHiddenWhereClause.Text = Session["whereClause"].ToString();
                txthiddenOrderbyClause.Text = Session["orderByClause"].ToString();
            }
            if (Session["pageIndex"] != null)
            {
                grdEquipment.PageIndex = Int32.Parse(Session["pageIndex"].ToString());
            }


            /* 
             * 1. number of equipments
             * 2. select the element 
             * */
            txtHiddenPageIndex.Text = "0";
        }
        else
        {
            txtHiddenPageIndex.Text = "0";
            DisplayPopUp("There are " +
                         (new DirectService().GetEquipmentWarrantyAlertBeforeMonth(
                             Int32.Parse(Resource.NumberOfMonthToAlert))).Rows.Count +
                         " equipments going to be out of warranty in " + Resource.NumberOfMonthToAlert + " month(s).");
        }
        grdEquipment.PageIndex = !String.IsNullOrEmpty(txtHiddenPageIndex.Text)
                                     ? Int32.Parse(txtHiddenPageIndex.Text)
                                     : 0;
    }


    protected void btnSearch_Click(object sender, EventArgs e)
    {
    }

    protected string GetWhereClause()
    {
        string whereClause = string.Empty;
        string and = "";
        string str = "";

        and = " and ";

        str = chkDamaged.Checked ? " EQUIPEMENT.Demaged= 1" : " EQUIPEMENT.Demaged= 0";


        // Prepare by equipement
        if (txtCodeNumber.Text != string.Empty)
        {
            str += and + "Equipement.codeNumber='" + txtCodeNumber.Text.Replace("'", "''").Trim() + "'";
            and = " and ";
        }
        if (txtPONumber.Text != string.Empty)
        {
            str += and + "EQUIPMENTPURCHASEINFORMATION.poreferencenumber='" + txtPONumber.Text.Replace("'", "''").Trim() +
                   "'";
            and = " and ";
        }

        if (txtPurchaseDate.Text != string.Empty)
        {
            str += and + "( EQUIPMENTPURCHASEINFORMATION.purchaseDate=convert(datetime,'" + txtPurchaseDate.Text +
                   "', 101) )";

            and = " and ";
        }
        //damaged 


        // prepare by system
        if (drlSystem.SelectedIndex > 0)
        {
            str += and + "System.SystemID=" + drlSystem.SelectedValue;
            and = " and ";
        }

        // prepare by type equipement
        if (drlEquipmentType.SelectedIndex > 0)
        {
            str += and + "TypeEquipment.TypeEquipementID=" + drlEquipmentType.SelectedValue;
            and = " and ";
        }
        // prepare by type equipement
        if (drlLocation.SelectedIndex > 0)
        {
            str += and + "Location.LocationId=" + drlLocation.SelectedValue;
            and = " and ";
        }

        // prepare by model
        if (drlModel.SelectedIndex > 0)
        {
            str += and + "Model.ModelID=" + drlModel.SelectedValue;
            and = " and ";
        }

        // prepare by model
        if (drlCompany.SelectedIndex > 0)
        {
            str += and + "EquipmentPurchaseInformation.companyID=" + drlCompany.SelectedValue;
            and = " and ";
        }

        // prepare by user
        if (drlUser.SelectedIndex > 0)
        {
            str += and + "employee.employeeid=" + drlUser.SelectedValue;
            and = " and ";
        }
        if (txtEndWarrantyDate.Text != string.Empty)
        {
            str += and + "( EQUIPMENTPURCHASEINFORMATION.DATEEND <= convert(datetime,'" + txtEndWarrantyDate.Text +
                   "', 101) )";

            and = " and ";
        }

        if (!String.IsNullOrEmpty(str))
            whereClause = " and " + str + " ";
        return whereClause;
    }

    protected string GetOrderClause()
    {
        return " Order by Equipement.codeNumber";
    }

    protected void btnValidate_Click(object sender, EventArgs e)
    {
        if (!new Utility().TestPermissions(Resource.PermissionViewEquipment))
        {
            lblMessageValidate.Text = Resource.Permission;
            lblTotalEquipment.Visible = false;
            return;
        }
        Session["whereClause"] = GetWhereClause();
        Session["orderByClause"] = GetOrderClause();
        txthiddenOrderbyClause.Text = GetOrderClause();
        txtHiddenWhereClause.Text = GetWhereClause();
        Session["defaultTabIndex"] = 0;
        ClearSearchTextBoxesData();
    }

    private void ClearSearchTextBoxesData()
    {
        txtCodeNumber.Text = string.Empty;
        txtPurchaseDate.Text = string.Empty;
        txtPONumber.Text = string.Empty;
        txtEndWarrantyDate.Text = string.Empty;
    }

    public string GetDisplayMode()
    {
        return Request.QueryString["detail"];
    }

    private void ResetSearchComponents()
    {
        drlCompany.SelectedIndex = 0;
        drlEquipmentType.SelectedIndex = 0;
        drlModel.SelectedIndex = 0;
        drlSystem.SelectedIndex = 0;
        drlUser.SelectedIndex = 0;
        txtCodeNumber.Text = string.Empty;
    }


    private void DisplayPopUp(string message)
    {
        popupWin.ActionType = PopupAction.OpenLink;

        // Set popup and window texts
        popupWin.Title = "Equipment alert";
        popupWin.Message = "<i>" + message + "</i>";

        popupWin.Text = "Text to show in new window..";


        // Change color style
        popupWin.ColorStyle = PopupColorStyle.Green;

        // Change timing
        popupWin.HideAfter = 20000;
        popupWin.ShowAfter = 500;

        // Show popup (after page is loaded)
        popupWin.Visible = true;
    }

    private void HidePopUp(string message)
    {
        popupWin.ActionType = PopupAction.OpenLink;

        // Set popup and window texts
        popupWin.Title = "Equipment alert";
        popupWin.Message = "<i>" + message + "</i>";

        popupWin.Text = "Text to show in new window..";


        // Change color style
        popupWin.ColorStyle = PopupColorStyle.Green;

        // Change timing
        popupWin.HideAfter = 20000;
        popupWin.ShowAfter = 0;


        // Show popup (after page is loaded)
    }

    public string GetAttachedParameters()
    {
        string param = string.Empty;

        param = "codeNumber=" + Request.QueryString["codeNumber"] +
                "&equipmentId=" + Request.QueryString["equipmentId"] +
                "&purchaseDate=" + Request.QueryString["purchaseDate"] +
                "&displayMode=" + Session["detail"];

        return param;
    }

    protected void grdEquipment_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        new Utility().SetSelectedColorToGridView(e, grdEquipment);
    }

    public int GetTabIndex()
    {
        int tabIndex = Request.QueryString["tabIndex"] != null
                           ?
                               Int32.Parse(Request.QueryString["tabIndex"])
                           : 0;
        if (Session["defaultTabIndex"] != null)
        {
            tabIndex = Int32.Parse(Session["defaultTabIndex"].ToString());
            Session["defaultTabIndex"] = null;
        }

        return tabIndex;
    }

    protected void grdEquipment_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdEquipment.PageIndex = e.NewPageIndex;
        txtHiddenPageIndex.Text = grdEquipment.PageIndex.ToString();
        Session["pageIndex"] = grdEquipment.PageIndex;
    }

    public int GetPageIndex()
    {
        return Session["pageIndex"] != null
                   ?
                       Int32.Parse(Session["pageIndex"].ToString())
                   : 0;
    }

    protected void grdEquipment_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdEquipment.EditIndex = -1;
    }

    protected void grdEquipment_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdEquipment.EditIndex = e.NewEditIndex;
    }

    protected void grdEquipment_SelectedIndexChanged1(object sender, EventArgs e)
    {
    }

    protected void grdEquipment_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes["onmouseover"] = "this.style.cursor='hand';this.style.textDecoration='underline';";
            e.Row.Attributes["onmouseout"] = "this.style.textDecoration='none';";
        }
    }

    protected void grdEquipment_SelectedIndexChanged(object sender, EventArgs e)
    {
    }

    protected void grdEquipment_Sorted(object sender, EventArgs e)
    {
        grdEquipment.DataBind();
    }

    protected void odsEquipment_Selected(object sender, ObjectDataSourceStatusEventArgs e)
    {
        lblTotalEquipment.Text = "Total Equipment : " +
                                 (e.ReturnValue != null
                                      ? ((DataTable) e.ReturnValue).Rows.Count.ToString()
                                      : 0.ToString());
        grdGroupeSoftware1.Visible = e.ReturnValue == null ? true : false;
    }

    protected void grdEquipment_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Select"))
        {
            int equipmentId = Convert.ToInt32(grdEquipment.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
            Session["equipmentId"] = equipmentId;
            Session["defaultTabIndex"] = 1;
            Session["rowSelectedIndex"] = Convert.ToInt32(e.CommandArgument);
        }
        new Utility().SetSelectedColorToGridView(e, grdEquipment);
    }

    protected void grdGroupeSoftware1_SelectedIndexChanged(object sender, EventArgs e)
    {
    }
}